import { useState, useRef, useEffect } from "react"

interface Timer {
  id: string
  name: string
  duration: number // 秒
  remaining: number // 秒
  isRunning: boolean
  isCompleted: boolean
  createdAt: Date
}

function IndexPopup() {
  const [isCapturing, setIsCapturing] = useState(false)
  const [screenshot, setScreenshot] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [activeTab, setActiveTab] = useState<'screenshot' | 'editor' | 'timer'>('screenshot')
  const [editorContent, setEditorContent] = useState('')
  const [isCapturingForEditor, setIsCapturingForEditor] = useState(false)
  const [timers, setTimers] = useState<Timer[]>([])
  const [newTimerName, setNewTimerName] = useState('')
  const [newTimerMinutes, setNewTimerMinutes] = useState(5)
  const editorRef = useRef<HTMLDivElement>(null)
  const fileInputRef = useRef<HTMLInputElement>(null)
  const intervalRef = useRef<NodeJS.Timeout | null>(null)

  // 定时器管理
  useEffect(() => {
    if (timers.some(timer => timer.isRunning)) {
      intervalRef.current = setInterval(() => {
        setTimers(prevTimers => {
          return prevTimers.map(timer => {
            if (timer.isRunning && timer.remaining > 0) {
              const newRemaining = timer.remaining - 1
              if (newRemaining <= 0) {
                // 定时器完成
                chrome.notifications?.create({
                  type: 'basic',
                  iconUrl: '/assets/icon.png',
                  title: '定时器提醒',
                  message: `"${timer.name}" 已完成！`
                })
                return { ...timer, remaining: 0, isRunning: false, isCompleted: true }
              }
              return { ...timer, remaining: newRemaining }
            }
            return timer
          })
        })
      }, 1000)
    } else {
      if (intervalRef.current) {
        clearInterval(intervalRef.current)
        intervalRef.current = null
      }
    }

    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current)
      }
    }
  }, [timers])

  // 格式化时间显示
  const formatTime = (seconds: number): string => {
    const hours = Math.floor(seconds / 3600)
    const minutes = Math.floor((seconds % 3600) / 60)
    const secs = seconds % 60
    
    if (hours > 0) {
      return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
    }
    return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }

  // 添加新定时器
  const addTimer = () => {
    if (!newTimerName.trim()) {
      alert('请输入定时器名称！')
      return
    }
    
    if (newTimerMinutes <= 0) {
      alert('定时器时间必须大于0！')
      return
    }

    const newTimer: Timer = {
      id: Date.now().toString(),
      name: newTimerName.trim(),
      duration: newTimerMinutes * 60,
      remaining: newTimerMinutes * 60,
      isRunning: false,
      isCompleted: false,
      createdAt: new Date()
    }

    setTimers(prev => [...prev, newTimer])
    setNewTimerName('')
    setNewTimerMinutes(5)
  }

  // 开始/暂停定时器
  const toggleTimer = (id: string) => {
    setTimers(prevTimers => 
      prevTimers.map(timer => 
        timer.id === id 
          ? { ...timer, isRunning: !timer.isRunning }
          : timer
      )
    )
  }

  // 重置定时器
  const resetTimer = (id: string) => {
    setTimers(prevTimers => 
      prevTimers.map(timer => 
        timer.id === id 
          ? { ...timer, remaining: timer.duration, isRunning: false, isCompleted: false }
          : timer
      )
    )
  }

  // 删除定时器
  const deleteTimer = (id: string) => {
    setTimers(prevTimers => prevTimers.filter(timer => timer.id !== id))
  }

  // 清空所有定时器
  const clearAllTimers = () => {
    if (timers.length === 0) return
    if (confirm('确定要清空所有定时器吗？')) {
      setTimers([])
    }
  }

  // HTML 转 Markdown 转换函数
  const htmlToMarkdown = (html: string): string => {
    let markdown = html

    // 处理标题
    markdown = markdown.replace(/<h1[^>]*>(.*?)<\/h1>/gi, '# $1\n\n')
    markdown = markdown.replace(/<h2[^>]*>(.*?)<\/h2>/gi, '## $1\n\n')
    markdown = markdown.replace(/<h3[^>]*>(.*?)<\/h3>/gi, '### $1\n\n')
    markdown = markdown.replace(/<h4[^>]*>(.*?)<\/h4>/gi, '#### $1\n\n')
    markdown = markdown.replace(/<h5[^>]*>(.*?)<\/h5>/gi, '##### $1\n\n')
    markdown = markdown.replace(/<h6[^>]*>(.*?)<\/h6>/gi, '###### $1\n\n')

    // 处理粗体和斜体
    markdown = markdown.replace(/<strong[^>]*>(.*?)<\/strong>/gi, '**$1**')
    markdown = markdown.replace(/<b[^>]*>(.*?)<\/b>/gi, '**$1**')
    markdown = markdown.replace(/<em[^>]*>(.*?)<\/em>/gi, '*$1*')
    markdown = markdown.replace(/<i[^>]*>(.*?)<\/i>/gi, '*$1*')

    // 处理下划线和删除线
    markdown = markdown.replace(/<u[^>]*>(.*?)<\/u>/gi, '<u>$1</u>')
    markdown = markdown.replace(/<s[^>]*>(.*?)<\/s>/gi, '~~$1~~')
    markdown = markdown.replace(/<strike[^>]*>(.*?)<\/strike>/gi, '~~$1~~')
    markdown = markdown.replace(/<del[^>]*>(.*?)<\/del>/gi, '~~$1~~')

    // 处理链接
    markdown = markdown.replace(/<a[^>]*href=["']([^"']*)["'][^>]*>(.*?)<\/a>/gi, '[$2]($1)')

    // 处理图片
    markdown = markdown.replace(/<img[^>]*src=["']([^"']*)["'][^>]*alt=["']([^"']*)["'][^>]*>/gi, '![$2]($1)')
    markdown = markdown.replace(/<img[^>]*alt=["']([^"']*)["'][^>]*src=["']([^"']*)["'][^>]*>/gi, '![$1]($2)')
    markdown = markdown.replace(/<img[^>]*src=["']([^"']*)["'][^>]*>/gi, '![]($1)')

    // 处理列表
    markdown = markdown.replace(/<ul[^>]*>(.*?)<\/ul>/gis, (match, content) => {
      const items = content.match(/<li[^>]*>(.*?)<\/li>/gis) || []
      return items.map((item: string) => {
        const text = item.replace(/<li[^>]*>(.*?)<\/li>/is, '$1')
        return `- ${htmlToMarkdown(text.trim())}`
      }).join('\n') + '\n\n'
    })

    markdown = markdown.replace(/<ol[^>]*>(.*?)<\/ol>/gis, (match, content) => {
      const items = content.match(/<li[^>]*>(.*?)<\/li>/gis) || []
      return items.map((item: string, index: number) => {
        const text = item.replace(/<li[^>]*>(.*?)<\/li>/is, '$1')
        return `${index + 1}. ${htmlToMarkdown(text.trim())}`
      }).join('\n') + '\n\n'
    })

    // 处理段落
    markdown = markdown.replace(/<p[^>]*>(.*?)<\/p>/gi, '$1\n\n')
    markdown = markdown.replace(/<div[^>]*>(.*?)<\/div>/gi, '$1\n\n')

    // 处理换行
    markdown = markdown.replace(/<br[^>]*>/gi, '\n')
    markdown = markdown.replace(/<\/br>/gi, '\n')

    // 处理代码
    markdown = markdown.replace(/<code[^>]*>(.*?)<\/code>/gi, '`$1`')
    markdown = markdown.replace(/<pre[^>]*>(.*?)<\/pre>/gis, '```\n$1\n```\n\n')

    // 处理引用
    markdown = markdown.replace(/<blockquote[^>]*>(.*?)<\/blockquote>/gis, (match, content) => {
      const lines = content.split('\n').filter((line: string) => line.trim())
      return lines.map((line: string) => `> ${htmlToMarkdown(line.trim())}`).join('\n') + '\n\n'
    })

    // 清理多余的标签和空白
    markdown = markdown.replace(/<[^>]*>/g, '')
    markdown = markdown.replace(/\n{3,}/g, '\n\n')
    markdown = markdown.replace(/^\s+|\s+$/g, '')

    return markdown
  }

  // 富文本编辑器功能
  const execCommand = (command: string, value?: string) => {
    document.execCommand(command, false, value)
    editorRef.current?.focus()
  }

  // 插入图片到编辑器的通用函数
  const insertImageToEditor = (imageSrc: string, altText: string = '图片') => {
    if (!editorRef.current) return

    // 确保编辑器获得焦点
    editorRef.current.focus()

    // 创建图片元素
    const img = document.createElement('img')
    img.src = imageSrc
    img.alt = altText
    img.style.maxWidth = '100%'
    img.style.height = 'auto'
    img.style.display = 'block'
    img.style.margin = '8px 0'
    img.style.borderRadius = '4px'
    img.style.boxShadow = '0 2px 4px rgba(0,0,0,0.1)'

    // 获取当前光标位置
    const selection = window.getSelection()
    if (selection && selection.rangeCount > 0) {
      const range = selection.getRangeAt(0)
      range.deleteContents()
      range.insertNode(img)
      
      // 将光标移到图片后面
      range.setStartAfter(img)
      range.setEndAfter(img)
      selection.removeAllRanges()
      selection.addRange(range)
    } else {
      // 如果没有选择，直接添加到编辑器末尾
      editorRef.current.appendChild(img)
      
      // 添加换行
      const br = document.createElement('br')
      editorRef.current.appendChild(br)
    }

    // 更新编辑器内容状态
    setEditorContent(editorRef.current.innerHTML)
  }

  // 插入网络图片
  const insertImageFromUrl = () => {
    const url = prompt('请输入图片URL:')
    if (url) {
      insertImageToEditor(url, '网络图片')
    }
  }

  // 插入本地图片
  const insertImageFromFile = () => {
    fileInputRef.current?.click()
  }

  // 处理文件选择
  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (!file) return

    // 检查文件类型
    if (!file.type.startsWith('image/')) {
      alert('请选择图片文件！')
      return
    }

    // 检查文件大小 (限制为 5MB)
    if (file.size > 5 * 1024 * 1024) {
      alert('图片文件大小不能超过 5MB！')
      return
    }

    const reader = new FileReader()
    reader.onload = (e) => {
      const result = e.target?.result as string
      if (result) {
        insertImageToEditor(result, file.name)
      }
    }
    reader.readAsDataURL(file)

    // 清空文件输入
    event.target.value = ''
  }

  // 浏览器截屏功能（用于编辑器）
  const captureScreenForEditor = async () => {
    try {
      setIsCapturingForEditor(true)
      setError(null)

      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true })
      
      if (!tab.id) {
        throw new Error("无法获取当前标签页")
      }

      const dataUrl = await chrome.tabs.captureVisibleTab(tab.windowId, {
        format: "png",
        quality: 100
      })

      insertImageToEditor(dataUrl, '浏览器截屏')
    } catch (err) {
      setError(err instanceof Error ? err.message : "截屏失败")
    } finally {
      setIsCapturingForEditor(false)
    }
  }

  const insertLink = () => {
    const url = prompt('请输入链接地址:')
    if (url) {
      execCommand('createLink', url)
    }
  }

  const clearFormatting = () => {
    execCommand('removeFormat')
  }

  const exportAsHTML = () => {
    if (!editorContent) return
    
    const blob = new Blob([editorContent], { type: 'text/html' })
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.download = `document-${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.html`
    link.href = url
    link.click()
    URL.revokeObjectURL(url)
  }

  const exportAsMarkdown = () => {
    if (!editorContent) return
    
    const markdown = htmlToMarkdown(editorContent)
    const blob = new Blob([markdown], { type: 'text/markdown' })
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.download = `document-${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.md`
    link.href = url
    link.click()
    URL.revokeObjectURL(url)
  }

  // 截屏功能（独立标签页）
  const captureScreen = async () => {
    try {
      setIsCapturing(true)
      setError(null)

      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true })
      
      if (!tab.id) {
        throw new Error("无法获取当前标签页")
      }

      const dataUrl = await chrome.tabs.captureVisibleTab(tab.windowId, {
        format: "png",
        quality: 100
      })

      setScreenshot(dataUrl)
    } catch (err) {
      setError(err instanceof Error ? err.message : "截屏失败")
    } finally {
      setIsCapturing(false)
    }
  }

  const downloadScreenshot = () => {
    if (!screenshot) return

    const link = document.createElement("a")
    link.download = `screenshot-${new Date().toISOString().slice(0, 19).replace(/:/g, "-")}.png`
    link.href = screenshot
    link.click()
  }

  const clearScreenshot = () => {
    setScreenshot(null)
    setError(null)
  }

  // 插入截屏到编辑器
  const insertScreenshotToEditor = () => {
    if (screenshot) {
      insertImageToEditor(screenshot, '截屏图片')
    }
  }

  return (
    <div
      style={{
        padding: 16,
        width: 400,
        minHeight: 300,
        fontFamily: "Arial, sans-serif"
      }}>
      
      {/* 隐藏的文件输入 */}
      <input
        ref={fileInputRef}
        type="file"
        accept="image/*"
        onChange={handleFileSelect}
        style={{ display: 'none' }}
      />
      
      {/* 标签页切换 */}
      <div style={{ 
        display: 'flex', 
        marginBottom: 16, 
        borderBottom: '1px solid #ddd' 
      }}>
        <button
          onClick={() => setActiveTab('screenshot')}
          style={{
            flex: 1,
            padding: '8px 12px',
            backgroundColor: activeTab === 'screenshot' ? '#007bff' : 'transparent',
            color: activeTab === 'screenshot' ? 'white' : '#333',
            border: 'none',
            borderBottom: activeTab === 'screenshot' ? '2px solid #007bff' : '2px solid transparent',
            cursor: 'pointer',
            fontSize: '14px'
          }}>
          📸 截屏
        </button>
        <button
          onClick={() => setActiveTab('editor')}
          style={{
            flex: 1,
            padding: '8px 12px',
            backgroundColor: activeTab === 'editor' ? '#007bff' : 'transparent',
            color: activeTab === 'editor' ? 'white' : '#333',
            border: 'none',
            borderBottom: activeTab === 'editor' ? '2px solid #007bff' : '2px solid transparent',
            cursor: 'pointer',
            fontSize: '14px'
          }}>
          ✏️ 编辑器
        </button>
        <button
          onClick={() => setActiveTab('timer')}
          style={{
            flex: 1,
            padding: '8px 12px',
            backgroundColor: activeTab === 'timer' ? '#007bff' : 'transparent',
            color: activeTab === 'timer' ? 'white' : '#333',
            border: 'none',
            borderBottom: activeTab === 'timer' ? '2px solid #007bff' : '2px solid transparent',
            cursor: 'pointer',
            fontSize: '14px'
          }}>
          ⏰ 定时器
        </button>
      </div>

      {/* 截屏标签页 */}
      {activeTab === 'screenshot' && (
        <div>
          <h3 style={{ marginTop: 0, color: "#333" }}>
            🖼️ 截屏工具
          </h3>
          
          <div style={{ marginBottom: 16 }}>
            <button
              onClick={captureScreen}
              disabled={isCapturing}
              style={{
                width: "100%",
                padding: "12px",
                backgroundColor: isCapturing ? "#ccc" : "#007bff",
                color: "white",
                border: "none",
                borderRadius: "6px",
                fontSize: "14px",
                cursor: isCapturing ? "not-allowed" : "pointer",
                marginBottom: "8px"
              }}>
              {isCapturing ? "截屏中..." : "📸 截取当前页面"}
            </button>
          </div>

          {error && (
            <div
              style={{
                padding: "8px",
                backgroundColor: "#f8d7da",
                color: "#721c24",
                borderRadius: "4px",
                marginBottom: "12px",
                fontSize: "12px"
              }}>
              ❌ {error}
            </div>
          )}

          {screenshot && (
            <div style={{ marginTop: 16 }}>
              <div style={{ marginBottom: 8 }}>
                <img
                  src={screenshot}
                  alt="截屏预览"
                  style={{
                    width: "100%",
                    maxHeight: "150px",
                    objectFit: "contain",
                    border: "1px solid #ddd",
                    borderRadius: "4px"
                  }}
                />
              </div>
              
              <div style={{ display: "flex", gap: "8px", marginBottom: 8 }}>
                <button
                  onClick={downloadScreenshot}
                  style={{
                    flex: 1,
                    padding: "8px",
                    backgroundColor: "#28a745",
                    color: "white",
                    border: "none",
                    borderRadius: "4px",
                    fontSize: "12px",
                    cursor: "pointer"
                  }}>
                  💾 下载
                </button>
                
                <button
                  onClick={clearScreenshot}
                  style={{
                    flex: 1,
                    padding: "8px",
                    backgroundColor: "#6c757d",
                    color: "white",
                    border: "none",
                    borderRadius: "4px",
                    fontSize: "12px",
                    cursor: "pointer"
                  }}>
                  🗑️ 清除
                </button>
              </div>

              <button
                onClick={insertScreenshotToEditor}
                style={{
                  width: "100%",
                  padding: "8px",
                  backgroundColor: "#17a2b8",
                  color: "white",
                  border: "none",
                  borderRadius: "4px",
                  fontSize: "12px",
                  cursor: "pointer"
                }}>
                📝 插入到编辑器
              </button>
            </div>
          )}
        </div>
      )}

      {/* 富文本编辑器标签页 */}
      {activeTab === 'editor' && (
        <div>
          <h3 style={{ marginTop: 0, color: "#333" }}>
            ✏️ 富文本编辑器
          </h3>

          {/* 工具栏 */}
          <div style={{ 
            display: 'flex', 
            flexWrap: 'wrap', 
            gap: '4px', 
            marginBottom: 12,
            padding: '8px',
            backgroundColor: '#f8f9fa',
            borderRadius: '4px',
            border: '1px solid #ddd'
          }}>
            <button
              onClick={() => execCommand('bold')}
              style={toolbarButtonStyle}
              title="粗体">
              <strong>B</strong>
            </button>
            <button
              onClick={() => execCommand('italic')}
              style={toolbarButtonStyle}
              title="斜体">
              <em>I</em>
            </button>
            <button
              onClick={() => execCommand('underline')}
              style={toolbarButtonStyle}
              title="下划线">
              <u>U</u>
            </button>
            <button
              onClick={() => execCommand('strikeThrough')}
              style={toolbarButtonStyle}
              title="删除线">
              <s>S</s>
            </button>
            
            <div style={{ width: '1px', backgroundColor: '#ddd', margin: '0 4px' }}></div>
            
            <button
              onClick={() => execCommand('justifyLeft')}
              style={toolbarButtonStyle}
              title="左对齐">
              ⬅️
            </button>
            <button
              onClick={() => execCommand('justifyCenter')}
              style={toolbarButtonStyle}
              title="居中">
              ↔️
            </button>
            <button
              onClick={() => execCommand('justifyRight')}
              style={toolbarButtonStyle}
              title="右对齐">
              ➡️
            </button>
            
            <div style={{ width: '1px', backgroundColor: '#ddd', margin: '0 4px' }}></div>
            
            <button
              onClick={() => execCommand('insertUnorderedList')}
              style={toolbarButtonStyle}
              title="无序列表">
              📋
            </button>
            <button
              onClick={() => execCommand('insertOrderedList')}
              style={toolbarButtonStyle}
              title="有序列表">
              🔢
            </button>
            
            <div style={{ width: '1px', backgroundColor: '#ddd', margin: '0 4px' }}></div>
            
            <button
              onClick={insertLink}
              style={toolbarButtonStyle}
              title="插入链接">
              🔗
            </button>
            
            {/* 图片插入按钮组 */}
            <div style={{ display: 'flex', gap: '2px' }}>
              <button
                onClick={insertImageFromUrl}
                style={toolbarButtonStyle}
                title="插入网络图片">
                🌐
              </button>
              <button
                onClick={insertImageFromFile}
                style={toolbarButtonStyle}
                title="插入本地图片">
                📁
              </button>
              <button
                onClick={captureScreenForEditor}
                disabled={isCapturingForEditor}
                style={{
                  ...toolbarButtonStyle,
                  backgroundColor: isCapturingForEditor ? '#ccc' : 'white',
                  cursor: isCapturingForEditor ? 'not-allowed' : 'pointer'
                }}
                title="截屏插入">
                📸
              </button>
            </div>
            
            <div style={{ width: '1px', backgroundColor: '#ddd', margin: '0 4px' }}></div>
            
            <button
              onClick={clearFormatting}
              style={toolbarButtonStyle}
              title="清除格式">
              🧹
            </button>
          </div>

          {/* 编辑器区域 */}
          <div
            ref={editorRef}
            contentEditable
            onInput={(e) => setEditorContent(e.currentTarget.innerHTML)}
            style={{
              minHeight: '200px',
              padding: '12px',
              border: '1px solid #ddd',
              borderRadius: '4px',
              backgroundColor: 'white',
              fontSize: '14px',
              lineHeight: '1.5',
              outline: 'none',
              overflowY: 'auto'
            }}
            dangerouslySetInnerHTML={{ __html: editorContent }}
          />

          {/* 编辑器操作按钮 */}
          <div style={{ display: 'flex', gap: '8px', marginTop: 12 }}>
            <button
              onClick={exportAsMarkdown}
              disabled={!editorContent.trim()}
              style={{
                flex: 1,
                padding: '8px',
                backgroundColor: editorContent.trim() ? '#6f42c1' : '#ccc',
                color: 'white',
                border: 'none',
                borderRadius: '4px',
                fontSize: '12px',
                cursor: editorContent.trim() ? 'pointer' : 'not-allowed'
              }}>
              📝 导出MD
            </button>
            
            <button
              onClick={exportAsHTML}
              disabled={!editorContent.trim()}
              style={{
                flex: 1,
                padding: '8px',
                backgroundColor: editorContent.trim() ? '#28a745' : '#ccc',
                color: 'white',
                border: 'none',
                borderRadius: '4px',
                fontSize: '12px',
                cursor: editorContent.trim() ? 'pointer' : 'not-allowed'
              }}>
              🌐 导出HTML
            </button>
            
            <button
              onClick={() => {
                setEditorContent('')
                if (editorRef.current) {
                  editorRef.current.innerHTML = ''
                }
              }}
              style={{
                flex: 1,
                padding: '8px',
                backgroundColor: '#dc3545',
                color: 'white',
                border: 'none',
                borderRadius: '4px',
                fontSize: '12px',
                cursor: 'pointer'
              }}>
              🗑️ 清空
            </button>
          </div>

          <div style={{ marginTop: 12, fontSize: '11px', color: '#666' }}>
            �� 提示：支持富文本格式，可插入网络图片、本地图片和浏览器截屏
          </div>
        </div>
      )}

      {/* 定时器标签页 */}
      {activeTab === 'timer' && (
        <div>
          <h3 style={{ marginTop: 0, color: "#333" }}>
            ⏰ 多任务定时器
          </h3>

          {/* 添加新定时器 */}
          <div style={{ 
            padding: '12px', 
            backgroundColor: '#f8f9fa', 
            borderRadius: '6px', 
            marginBottom: 16,
            border: '1px solid #ddd'
          }}>
            <div style={{ marginBottom: 8 }}>
              <input
                type="text"
                placeholder="定时器名称"
                value={newTimerName}
                onChange={(e) => setNewTimerName(e.target.value)}
                style={{
                  width: '100%',
                  padding: '8px',
                  border: '1px solid #ddd',
                  borderRadius: '4px',
                  fontSize: '14px',
                  marginBottom: '8px'
                }}
              />
            </div>
            <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
              <input
                type="number"
                min="1"
                max="1440"
                value={newTimerMinutes}
                onChange={(e) => setNewTimerMinutes(Number(e.target.value))}
                style={{
                  width: '80px',
                  padding: '8px',
                  border: '1px solid #ddd',
                  borderRadius: '4px',
                  fontSize: '14px'
                }}
              />
              <span style={{ fontSize: '14px', color: '#666' }}>分钟</span>
              <button
                onClick={addTimer}
                style={{
                  flex: 1,
                  padding: '8px 12px',
                  backgroundColor: '#28a745',
                  color: 'white',
                  border: 'none',
                  borderRadius: '4px',
                  fontSize: '14px',
                  cursor: 'pointer'
                }}>
                ➕ 添加定时器
              </button>
            </div>
          </div>

          {/* 定时器列表 */}
          <div style={{ maxHeight: '300px', overflowY: 'auto' }}>
            {timers.length === 0 ? (
              <div style={{ 
                textAlign: 'center', 
                color: '#666', 
                padding: '20px',
                fontSize: '14px'
              }}>
                📝 还没有定时器，添加一个开始使用吧！
              </div>
            ) : (
              timers.map((timer) => (
                <div
                  key={timer.id}
                  style={{
                    padding: '12px',
                    border: '1px solid #ddd',
                    borderRadius: '6px',
                    marginBottom: '8px',
                    backgroundColor: timer.isCompleted ? '#d4edda' : 'white'
                  }}>
                  <div style={{ 
                    display: 'flex', 
                    justifyContent: 'space-between', 
                    alignItems: 'center',
                    marginBottom: '8px'
                  }}>
                    <h4 style={{ 
                      margin: 0, 
                      fontSize: '14px',
                      color: timer.isCompleted ? '#155724' : '#333'
                    }}>
                      {timer.name}
                    </h4>
                    <button
                      onClick={() => deleteTimer(timer.id)}
                      style={{
                        padding: '4px 8px',
                        backgroundColor: '#dc3545',
                        color: 'white',
                        border: 'none',
                        borderRadius: '3px',
                        fontSize: '12px',
                        cursor: 'pointer'
                      }}>
                      🗑️
                    </button>
                  </div>
                  
                  <div style={{ 
                    fontSize: '18px', 
                    fontWeight: 'bold',
                    color: timer.isCompleted ? '#155724' : '#007bff',
                    marginBottom: '8px',
                    textAlign: 'center'
                  }}>
                    {formatTime(timer.remaining)}
                  </div>
                  
                  <div style={{ 
                    display: 'flex', 
                    gap: '8px',
                    justifyContent: 'center'
                  }}>
                    <button
                      onClick={() => toggleTimer(timer.id)}
                      disabled={timer.isCompleted}
                      style={{
                        padding: '6px 12px',
                        backgroundColor: timer.isRunning ? '#dc3545' : '#28a745',
                        color: 'white',
                        border: 'none',
                        borderRadius: '4px',
                        fontSize: '12px',
                        cursor: timer.isCompleted ? 'not-allowed' : 'pointer',
                        opacity: timer.isCompleted ? 0.6 : 1
                      }}>
                      {timer.isRunning ? '⏸️ 暂停' : '▶️ 开始'}
                    </button>
                    
                    <button
                      onClick={() => resetTimer(timer.id)}
                      style={{
                        padding: '6px 12px',
                        backgroundColor: '#6c757d',
                        color: 'white',
                        border: 'none',
                        borderRadius: '4px',
                        fontSize: '12px',
                        cursor: 'pointer'
                      }}>
                      🔄 重置
                    </button>
                  </div>
                  
                  {timer.isCompleted && (
                    <div style={{ 
                      textAlign: 'center', 
                      marginTop: '8px',
                      fontSize: '12px',
                      color: '#155724',
                      fontWeight: 'bold'
                    }}>
                      ✅ 已完成！
                    </div>
                  )}
                </div>
              ))
            )}
          </div>

          {/* 清空所有定时器 */}
          {timers.length > 0 && (
            <button
              onClick={clearAllTimers}
              style={{
                width: '100%',
                padding: '8px',
                backgroundColor: '#dc3545',
                color: 'white',
                border: 'none',
                borderRadius: '4px',
                fontSize: '12px',
                cursor: 'pointer',
                marginTop: '12px'
              }}>
              🗑️ 清空所有定时器
            </button>
          )}

          <div style={{ marginTop: 12, fontSize: '11px', color: '#666' }}>
            💡 提示：定时器完成后会显示系统通知提醒
          </div>
        </div>
      )}
    </div>
  )
}

// 工具栏按钮样式
const toolbarButtonStyle = {
  padding: '4px 8px',
  backgroundColor: 'white',
  border: '1px solid #ddd',
  borderRadius: '3px',
  cursor: 'pointer',
  fontSize: '12px',
  minWidth: '24px',
  height: '24px',
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center'
}

export default IndexPopup
